package com.codebattery.service;


import com.codebattery.config.RabbitMQConfig;
import com.codebattery.domain.model.SecOrder;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FlashSaleService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FlashSaleService.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public String sale(String userId, String goodsId){
        LOGGER.info("参加秒杀的用户是：{}，秒杀的商品是：{}", userId, goodsId);
        String message = null;
        //调用redis给相应商品库存量减一
//        Long decrByResult = redisService.decrBy(cName);
//        if (decrByResult >= 0) {
            /**
             * 说明该商品的库存量有剩余，可以进行下订单操作
             */
//            LOGGER.info("用户：{}秒杀该商品：{}库存有余，可以进行下订单操作", username, cName);
            //发消息给库存消息队列，将库存数据减一
//            rabbitTemplate.convertAndSend(RabbitMQConfig.STORY_EXCHANGE, RabbitMQConfig.STORY_ROUTING_KEY, cName);

            //发消息给订单消息队列，创建订单
            SecOrder order = new SecOrder();
            order.setUserId(userId);
            order.setGoodsId(goodsId);

            // 消息唯一ID
            CorrelationData correlationData = new CorrelationData();

            for(int i=0; i< 1000000; i++){
                rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EXCHANGE,
                        RabbitMQConfig.ORDER_ROUTING_KEY,
                        JSONObject.fromObject(order), correlationData);
            }
            message = "用户" + userId + "秒杀" + goodsId + "成功";
//        } else {
//            /**
//             * 说明该商品的库存量没有剩余，直接返回秒杀失败的消息给用户
//             */
            LOGGER.info("用户：{}秒杀时商品的库存量没有剩余,秒杀结束", userId);
            message = "用户："+ userId + "商品的库存量没有剩余,秒杀结束";
//        }
        return message;
    }

}
